<template>
    <div class="page">
      <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
            <!-- 搜索框-->
         <!-- <el-form-item prop="company.id">
            <SelectTree
                  ref="company.id"
                  :props="{
                      value: 'id',             // ID字段名
                      label: 'name',         // 显示名称
                      children: 'children'    // 子级字段名
                    }"
                  placeholder="请选择公司"
                  size="small"
                  :url="`/sys/office/treeData?type=2`"
                  :value="searchForm.company.id"
                  :clearable="true"
                  :accordion="true"
                  @getValue="(value) => {searchForm.company.id=value}"/>
         </el-form-item> -->
         <el-form-item prop="department.id">
            <SelectTree
                  ref="department.id"
                  :props="{
                      value: 'id',             // ID字段名
                      label: 'name',         // 显示名称
                      children: 'children'    // 子级字段名
                    }"
                  placeholder="请选择部门"
                  size="small"
                  :url="`/sys/office/treeData?type=2`"
                  :value="searchForm.department.id"
                  :clearable="true"
                  :accordion="true"
                  @getValue="(value) => {searchForm.department.id=value}"/>
         </el-form-item>
         <el-form-item prop="isloan">
                  <el-select v-model="searchForm.isloan" placeholder="请选择是否借款" size="small" style="width: 100%;">
                    <el-option
                      v-for="item in $dictUtils.getDictList('yes_no')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
         </el-form-item>
         <el-form-item prop="ispay">
                  <el-select v-model="searchForm.ispay" placeholder="请选择是否还清" size="small" style="width: 100%;">
                    <el-option
                      v-for="item in $dictUtils.getDictList('yes_no')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
         </el-form-item>
         <!-- <el-form-item prop="recordunique">
                <el-input size="small" v-model="searchForm.recordunique" placeholder="应收报表唯一标识" clearable></el-input>
         </el-form-item>
         <el-form-item prop="personalborrowmoney">
                <el-input size="small" v-model="searchForm.personalborrowmoney" placeholder="借款申请id" clearable></el-input>
         </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
            <el-button @click="resetSearch()" size="small">重置</el-button>
          </el-form-item>
      </el-form>
        <!-- 导入导出-->
      <el-dialog  title="导入Excel" :visible.sync="isImportCollapse">
          <el-form size="small" :inline="true" v-show="isImportCollapse"  ref="importForm">
             <el-form-item>
              <el-button type="default" @click="downloadTpl()" size="small">下载模板</el-button>
             </el-form-item>
             <el-form-item prop="loginName">
                <el-upload
                  class="upload-demo"
                  :action="`${this.$http.BASE_URL}/rf/receiveother/receiveOther/import`"
                  :on-success="uploadSuccess"
                   :show-file-list="true">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只允许导入“xls”或“xlsx”格式文件！</div>
                </el-upload>
            </el-form-item>
          </el-form>
      </el-dialog>
      <div class="bg-white top">
      <!-- <el-row>
        <el-button v-if="hasPermission('rf:receiveother:receiveOther:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
        <el-button v-if="hasPermission('rf:receiveother:receiveOther:edit')" type="warning" size="small" icon="el-icon-edit-outline" @click="edit()"
         :disabled="dataListSelections.length != 1" plain>修改</el-button>
        <el-button v-if="hasPermission('rf:receiveother:receiveOther:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()"
                  :disabled="dataListSelections.length <= 0" plain>删除
        </el-button>
        <el-button-group class="pull-right">
            <el-button v-if="hasPermission('rf:receiveother:receiveOther:import')" type="default" size="small" icon="el-icon-upload2" title="导入" @click="isImportCollapse = !isImportCollapse"></el-button>
            <el-button v-if="hasPermission('rf:receiveother:receiveOther:export')" type="default" size="small" icon="el-icon-download" title="导出" @click="exportExcel()"></el-button>
            <el-button
              type="default"
              size="small"
              icon="el-icon-refresh"
              @click="refreshList">
            </el-button>
        </el-button-group>
      </el-row> -->
    <el-table
      :data="dataList"
      size="small"
      :cell-style="cellStyle"
      :header-cell-class-name="cellHeadStyle"
      :row-class-name="tableRowClassName"
      style="width:100%; border:1px solid #d6cfe2;"
       height="calc(100% - 80px)"
      @selection-change="selectionChangeHandle"
      @sort-change="sortChangeHandle"
      v-loading="loading"
      class="table">
      <!-- <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column> -->
      <!-- <el-table-column
        prop="company.name"
        show-overflow-tooltip
        align="center"
        min-width="120"
        label="公司">
            <template slot-scope="scope">
              <el-link  type="primary" :underline="false" v-if="hasPermission('rf:receiveother:receiveOther:edit')" @click="edit(scope.row.id)">{{scope.row.company.name}}</el-link>
              <el-link  type="primary" :underline="false" v-else-if="hasPermission('rf:receiveother:receiveOther:view')"  @click="view(scope.row.id)">{{scope.row.company.name}}</el-link>
              <span v-else>{{scope.row.company.name}}</span>
            </template>
      </el-table-column> -->
      <el-table-column
        prop="user.name"
        show-overflow-tooltip
        align="center"
        label="借款人">
          <template slot-scope="scope">
            <el-link  type="primary" :underline="false"  @click="view(scope.row.id)">{{scope.row.user.name}}</el-link>              
          </template>
      </el-table-column>
      <el-table-column
        prop="department.name"
        show-overflow-tooltip
        align="center"
        label="部门">
      </el-table-column>
    <el-table-column
        prop="isloan"
        show-overflow-tooltip
        align="center"
        label="是否借款">
        <template slot-scope="scope">
              {{ $dictUtils.getDictLabel("yes_no", scope.row.isloan, '-') }}
        </template>
      </el-table-column>
    <el-table-column
        prop="loanamount"
        show-overflow-tooltip
        align="center"
        label="借款金额">
      </el-table-column>
    <el-table-column
        prop="loandate"
        show-overflow-tooltip
        align="center"
        label="借款日期">
      </el-table-column>
    <el-table-column
        prop="expectrepay"
        show-overflow-tooltip
        align="center"
        label="预计还款日期">
      </el-table-column>
    <el-table-column
        prop="repaydate"
        show-overflow-tooltip
        align="center"
        label="还款日期">
      </el-table-column>
    <el-table-column
        prop="ispay"
        show-overflow-tooltip
        align="center"
        label="是否还清">
        <template slot-scope="scope">
              {{ $dictUtils.getDictLabel("yes_no", scope.row.ispay, '-') }}
        </template>
      </el-table-column>
    <!-- <el-table-column
        prop="recordunique"
        show-overflow-tooltip
        align="center"
        label="应收报表唯一标识">
      </el-table-column>
    <el-table-column
        prop="personalborrowmoney"
        show-overflow-tooltip
        align="center"
        label="借款申请id">
      </el-table-column> -->
    <el-table-column
        prop="repaymentamount"
        show-overflow-tooltip
        align="center"
        label="还款金额">
      </el-table-column>
    <el-table-column
        prop="remarks"
        show-overflow-tooltip
        align="center"
        label="备注信息">
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        fixed="right"
        :key="Math.random()"
        width="100"
        label="操作">
        <template  slot-scope="scope">
          <!-- <el-button v-if="hasPermission('rf:receiveother:receiveOther:view')" type="text" icon="el-icon-view" size="small" @click="view(scope.row.id)">查看</el-button>
          <el-button v-if="hasPermission('rf:receiveother:receiveOther:edit')" type="text" icon="el-icon-edit" size="small" @click="edit(scope.row.id)">修改</el-button>
          <el-button v-if="hasPermission('rf:receiveother:receiveOther:del')" type="text"  icon="el-icon-delete" size="small" @click="del(scope.row.id)">删除</el-button> -->
          <el-button type="text"  icon="el-icon-document-remove" size="small" @click="charge(scope.row)"  :disabled="financeDis || scope.row.ispay==0">冲销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="冲销信息"
      :visible.sync="dialogVisible"
      width="40%" >
      <el-form size="small" :inline="true"   :model="borrowMoney" @keyup.enter.native="getBorrowMoney()" @submit.native.prevent ref="borrowMoney">
        <el-col :span="12">
          <el-form-item  size="small"  prop="repaymentamount"  label="冲销金额"  label-width="110px"  :rules="[{ required: true,message: '请输入冲销金额(最多保留两位小数)',trigger: 'blur',pattern: /^\d*\.?(\d|\d{2})$/ }]">
            <el-input v-model="borrowMoney.repaymentamount"  autocomplete="off" @input="judgeCharge"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  size="small"  prop="remarks"  label="说明"  label-width="110px" :rules="[{ required: true,message: '请输入说明',trigger: 'blur',}]">
            <el-input v-model="borrowMoney.remarks"   autocomplete="off"></el-input>
          </el-form-item>
        </el-col>		
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDialogVisible">取 消</el-button >
          <el-button size="small" type="primary" @click="confirmBorrow">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      background
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    </div>
        <!-- 弹窗, 新增 / 修改 -->
    <ReceiveOtherForm  ref="receiveOtherForm" @refreshDataList="refreshList"></ReceiveOtherForm>
  </div>
</template>

<script>
  import ReceiveOtherForm from './ReceiveOtherForm'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import tableStyles from '../../../../utils/mixins'
  export default {
    mixins: [tableStyles],
    data () {
      return {
        searchForm: {
          company: {
            id: ''
          },
          department: {
            id: ''
          },
          isloan: '',
          ispay: '',
          recordunique: '',
          personalborrowmoney: ''
        },
        dataList: [],
        pageNo: 1,
        pageSize: 10,
        total: 0,
        orderBy: '',
        dataListSelections: [],
        isImportCollapse: false,
        loading: false,
        dialogVisible:false,//冲销弹出框
        borrowMoney:{
          repaymentamount:'',
          remarks:''
        },
        borrowId:'',//冲销id
        borrowCompangId:'',//公司id
        financeDis:true,//是否为财务,
        nowLoanamount:'',//当前点击冲销的借款
        nowRepaymentamount:'',//当前点击冲销的还款
      }
    },
    components: {
      SelectTree,
      ReceiveOtherForm
    },
    // watch:{
    //   '$route'(to,form){
    //     if(to.query.borrowCompangId){
    //       this.refreshList();
    //     }     
    //   }
    // },
    activated () {
      this.refreshList();
      this.getfinancePower();
    },
    created(){
      window.addEventListener("beforeunload",()=>{
        sessionStorage.setItem("userInfo",JSON.stringify(this.$store.state.user))
      })
    },
    methods: {
      //判断冲销金额是否符合 借款-还款 剩余
      judgeCharge(){
        if(this.borrowMoney.repaymentamount>(Number(this.nowLoanamount)-Number(this.nowRepaymentamount))){
          this.$message.warning('已超出最大冲销额度并已填充最大额度');
          this.borrowMoney.repaymentamount=Number(this.nowLoanamount)-Number(this.nowRepaymentamount)
        }

      },
      //查询该用户是否为财务，是否具有冲销权限
      getfinancePower(){
        if(this.$store.state.user.id!=''){
            var users=this.$store.state.user
        }else{
          var users=JSON.parse(sessionStorage.getItem("userInfo"));
        }
        this.$http({
          url: `/rf/receive/getApprovalPower`,
          method: 'get',
          params:{
            userid:users.id,
          }
        }).then(({data}) => {
          if (data  && data.isUpdate==1) {
            this.financeDis=true;
          }else if(data  && data.isUpdate==0) {
            this.financeDis=false;
          }
        })
      }, 
      //确认
      confirmBorrow(){
        this.$http({
          url: '/rf/receive/updateRepaymentMoney',
          method: 'post',
          params: {
            'repaymentamount': this.borrowMoney.repaymentamount,
            'remarks': this.borrowMoney.remarks,
            'id': this.borrowId,
          }
        }).then(({data}) => {
          // console.log(data,'1')
          if (data && data.success) {
            this.dialogVisible=false;
            this.$refs.borrowMoney.resetFields();
            this.refreshList();
          }
        })
      },
      //取消按钮
      closeDialogVisible(){
        this.dialogVisible=false;
        this.$refs.borrowMoney.resetFields();
      },
      //冲销按钮
      charge(row){
        this.dialogVisible=true;
        this.borrowId=row.id;   
        this.nowLoanamount=row.loanamount;//当前点击冲销的借款
        this.nowRepaymentamount=row.repaymentamount;//当前点击冲销的还款
      },     
      // 获取数据列表
      refreshList () {
        this.searchForm.company.id=this.$route.query.borrowCompangId
        this.loading = true
        this.$http({
          url: '/rf/receiveother/receiveOther/list',
          method: 'get',
          params: {
            'pageNo': this.pageNo,
            'pageSize': this.pageSize,
            'orderBy': this.orderBy,
            'company':this.$route.query.borrowCompangId,
            ...this.searchForm
          }
        }).then(({data}) => {
          if (data && data.success) {
            this.dataList = data.page.list
            this.total = data.page.count
            this.loading = false
          }
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageNo = 1
        this.refreshList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageNo = val
        this.refreshList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },

    // 排序
      sortChangeHandle (obj) {
        if (obj.order === 'ascending') {
          this.orderBy = obj.prop + ' asc'
        } else if (obj.order === 'descending') {
          this.orderBy = obj.prop + ' desc'
        } else {
          this.orderBy = ''
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.receiveOtherForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.dataListSelections.map(item => {
          return item.id
        })[0]
        this.$refs.receiveOtherForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.receiveOtherForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.dataListSelections.map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http({
            url: '/rf/receiveother/receiveOther/delete',
            method: 'delete',
            params: {'ids': ids}
          }).then(({data}) => {
            if (data && data.success) {
              this.$message.success(data.msg)
              this.refreshList()
            }
            this.loading = false
          })
        })
      },
      // 导入成功
      uploadSuccess (res, file) {
        if (res.success) {
          this.$message.success({dangerouslyUseHTMLString: true,
            message: res.msg})
        } else {
          this.$message.error(res.msg)
        }
      },
      // 下载模板
      downloadTpl () {
        this.$utils.download('/rf/receiveother/receiveOther/import/template')
      },
      exportExcel () {
        let params = {
          ...this.searchForm
        }
        this.$utils.download('/rf/receiveother/receiveOther/export', params)
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      }
    }
  }
</script>